package com.eastfair.security.resolver;

import com.eastfair.annotation.annotation.user.LoginUser;
import com.eastfair.core.context.ContextConstants;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.security.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Token转化为用户信息 放入到指定的controller参数中
 *
 * @author ligang
 * @date 2018/12/21
 */
@Slf4j
public class ContextArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 入参筛选
     *
     * @param mp 参数集合
     * @return 格式化后的参数
     */
    @Override
    public boolean supportsParameter(MethodParameter mp) {
        //mp.hasParameterAnnotation(LoginUser.class) &&
        return mp.hasParameterAnnotation(LoginUser.class) && mp.getParameterType().equals(SysUser.class);
    }

    /**
     * @param methodParameter       入参集合
     * @param modelAndViewContainer model 和 view
     * @param nativeWebRequest      web相关
     * @param webDataBinderFactory  入参解析
     * @return 包装对象
     */
    @Override
    public Object resolveArgument(@NonNull MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  @NonNull NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String account = request.getHeader(ContextConstants.JWT_KEY_ACCOUNT);
        String userid = request.getHeader(ContextConstants.JWT_KEY_USER_ID);
        String name = request.getHeader(ContextConstants.JWT_KEY_NAME);
        String projectid = request.getHeader(ContextConstants.JWT_KEY_PROJECT_ID);
        ContextUtil.setUserId(StringUtils.isNotBlank(userid)?Long.parseLong(userid):0);
        ContextUtil.setAccount(account);
        ContextUtil.setName(name);
        ContextUtil.setProjectId(StringUtils.isNotBlank(projectid)?Long.parseLong(projectid):null);
        ContextUtil.setTrace(request.getHeader(ContextConstants.TRACE_ID_HEADER));
        //以下代码为 根据 @LoginUser 注解来注入 SysUser 对象
        SysUser user = SysUser.builder()
                .id(ContextUtil.getUserId())
                .account(account)
                .name(name)
                .projectId(ContextUtil.getProjectId())
                .build();
        try {
//            LoginUser loginUser = methodParameter.getParameterAnnotation(LoginUser.class);
//            boolean isQuery = BooleanUtil.or(loginUser.isFull(), loginUser.isStation(), loginUser.isOrg(),
//                    loginUser.isRoles(), loginUser.isResource());
//            boolean isQuery =true;
//            if (isQuery) {
//                UserResolverService userResolverService = SpringUtils.getBean(UserResolverService.class);
//                R<SysUser> result = userResolverService.getById(userId,
//                        UserQuery.builder()
//                                .full(loginUser.isFull())
//                                .org(loginUser.isOrg())
//                                .station(loginUser.isStation())
//                                .roles(loginUser.isRoles())
//                                .resource(loginUser.isResource())
//                                .build());
//                if (result.getIsSuccess() && result.getData() != null) {
//                    return result.getData();
//                }
//            }

            return user;
        } catch (Exception e) {
            log.warn("注入登录人信息时，发生异常. --> {}", user, e);
        }

        return user;
    }

}
